<?php

namespace app\admin\controller\language;

use app\common\controller\Backend;
use app\logic\language\LangLogic;

/**
 * 语言包翻译
 */
class Translate extends Backend
{
    /**
     * Translate模型对象
     * @var object
     * @phpstan-var \app\admin\model\language\Translate
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected array $withJoinTable = ['language', 'languageKeywords'];

    protected string|array $quickSearchField = ['languageKeywords.keyword'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\language\Translate();
    }

    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

    /**
     * 清除语言包缓存
     * @return void
     */
    public function clearLangCache()
    {
        LangLogic::clearLangCache();
        $this->success(__('success'));
    }

    /**
     * 同步需要翻译的语言包关键词
     */
    public function syncTranslate()
    {

        $status = LangLogic::syncTranslate();

        if (!$status) {
            $this->error(__('fail'));
        }

        $this->success(__('success'));
    }

    /**
     * 发布语言包
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function publish()
    {
        LangLogic::clearLangCache();

        $langList = LangLogic::getLangList();

        foreach ($langList as $lang) {
            $dir = public_path('lang');
            if (!is_dir($dir)) {
                mkdir($dir, 0755, true);
            }
            $langData = LangLogic::getLang($lang['lang']);
            $filePath = $dir.'/' . $lang['lang'] . '.json';
            file_put_contents($filePath, json_encode($langData, JSON_UNESCAPED_UNICODE));
        }

        $this->success(__('Publish Success'));
    }
}